#!/usr/bin/python
"""Script to display a system-tray icon showing recording status

Based on code from:
	http://mythtv.org/wiki/index.php/Using_System_LEDs_for_Recording_Status and http://blog.vrplumber.com/810
"""
import commands, time, glob, urllib
from StringIO import StringIO
import pprint
import xml.dom.minidom
from xml.dom.minidom import Node
import datetime
import os
import sys
import re
import string

if os.path.isfile(os.path.join(os.getenv("HOME"), '.mythtv/mythbackend-notifier.config')):
     fi = open(os.path.join(os.getenv("HOME"), '.mythtv/mythbackend-notifier.config'))	
     for line in fi:
     	if re.compile("^BackendIP").search(line):
                    text=string.split(string.split(line,"=")[1],'\n')[0]
                    backendip = text
     	elif re.compile("^Port").search(line):
                    text=string.split(string.split(line,"=")[1],'\n')[0]
                    port = text
else:
	try:
	        fi = open(os.path.join(os.getenv("HOME"), '.mythtv/mythbackend-notifier.config'), 'w')
	except IOError:
	        print 'Can\'t open file for writing.'
	        sys.exit(0)
	defaultBackendIP = "127.0.0.1"  
	defaultPort = "6544"
	backendip = raw_input("Backend IP Address (Default is: "+defaultBackendIP+"): ")
	if backendip == "":
		backendip = defaultBackendIP
	port = raw_input("Port Number (Default 6544): ")
	if port == "":
		port = defaultPort	
	wbackendip = "BackendIP="+backendip
	wport = "Port="+port
	fi.write(wbackendip+"\n")
	fi.write(wport)

protocol = "http"
target = protocol+"://"+backendip+":"+port+"/xml"
page = urllib.urlopen(target).read()
doc = xml.dom.minidom.parseString(page)

fi.close()

def getEncodersCount():
	for node in doc.getElementsByTagName("Encoders"):
	 	encoders_count = node.getAttribute("count")
	return encoders_count

def activeVideoDevices( ):
	for node in doc.getElementsByTagName("Encoder"):
	 	state = node.getAttribute("state")
	return state

if __name__ == "__main__":
	import wx
	

	class RDApp( wx.App ):
		duration = 20 # seconds
		def OnInit( self ):

			"""Initialise, kicking off our operations"""
			self.frame = wx.Frame( None, -1, 'RecordingDevicesApp' )
			self.icon = wx.TaskBarIcon()
			wx.EVT_TASKBAR_LEFT_DCLICK( self.icon, self.OnClickIcon )
			class MyTimer( wx.Timer ):
				def Notify( self, event=None ):
					wx.GetApp().MainOperation(event)
			self.timer = MyTimer(  )
			
			# fire every self.duration seconds 
			self.timer.Start( self.duration * 1000, False ) 
			self.frame.Show( False )
			self.SetTopWindow( self.frame )
			self.MainOperation(None)
			return True
		
		def MainOperation( self, event ):
			"""Check every few seconds for current status"""
			self.setStatus( activeVideoDevices() )
		
		def setStatus( self, recording ):
			"""Set the icon's current representation"""

			for node in doc.getElementsByTagName("Encoder"):
	 			encoderNumber = node.getAttribute("id")
	 		 	state = node.getAttribute("state")
	 		 	L = node.getElementsByTagName("Program")
			 	for node2 in L:
	 				title = node2.getAttribute("title")
	 			 	endtime = node2.getAttribute("endTime")
	 			 	hostname = node2.getAttribute("hostname")
					starttime = node2.getAttribute("startTime")
					
					tuple_endtime = time.strptime(endtime, "%Y-%m-%dT%H:%M:%S")
					tuple_starttime = time.strptime(starttime, "%Y-%m-%dT%H:%M:%S")			
					tuple_currenttime = time.localtime()
					#print tuple_endtime

					remaining_time_in_sec = time.mktime(tuple_endtime) - time.mktime(tuple_currenttime)
					total_time_in_sec = time.mktime(tuple_endtime) - time.mktime(tuple_starttime)
					remaining_time = datetime.timedelta(seconds=remaining_time_in_sec)
					total_time = datetime.timedelta(seconds=total_time_in_sec)			
					#print remaining_time
					#print total_time

					#print remaining_time +" of "+total_time+" = " 
					percentage = 100 - (remaining_time_in_sec/total_time_in_sec*100 )
					print percentage 
		
			# This lists 10 upcoming recordings
						
			for node in doc.getElementsByTagName("Program"):
	 		 	titleList = node.getAttribute("title")
	 		 	L = node.getElementsByTagName("Channel")
			 	for node2 in L:
	 				channel = node2.getAttribute("callSign")
				#print titleList +" on "+ channel #uncomment to show the upcoming recordings
	 		
			width = 16
			bitmap = wx.EmptyBitmap(width, width)
			dc = wx.MemoryDC( )
			dc.SelectObject( bitmap )
			try:
				dc.SetBackground( wx.BLUE_BRUSH )
				dc.Clear()
#				print recording
				if recording != "0":
					if recording == "1":
						message = "Watching LiveTV: "+title+" on "+hostname+" using tuner "+encoderNumber+ " until " +endtime 
						brush = wx.GREEN_BRUSH
						myHeigh=int(width*percentage/100)
						#print myHeigh
						dc.DrawLine(0,width,0,myHeigh)
						print message						
					elif recording == "4":
						message = "One recording in process: "+title+" on "+hostname+" using tuner "+encoderNumber+ " until " +endtime
						brush = wx.RED_BRUSH
						myHeigh=int(width*percentage/100)
						#print myHeigh
						dc.DrawLine(0,width,0,myHeigh)
						print message
				else:
					brush = wx.BLACK_BRUSH
					message = "No recording currently"
					print message
				dc.SetBrush( brush )
				dc.DrawCircle( width/2,width/2,width/2-2 )
			finally:
				dc.SelectObject( wx.NullBitmap )
			bitmap.SetMaskColour( wx.BLUE )
			icon = wx.IconFromBitmap(bitmap)
			self.icon.SetIcon( icon, message )
		def OnClickIcon( self, event ):
			"""Handle double-click of icon (close)"""
			self.icon.RemoveIcon()
			self.frame.Close()

	app = RDApp()
	app.MainLoop()
	

